/**
 * 背调联系人
 */
import React, { useState } from 'react';
import { InputItem, Toast, TextareaItem, DatePicker, Modal } from 'antd-mobile';
import { Spin, message } from 'antd';
import { connect } from 'umi';
import { router, withRouter } from 'umi';
import moment from 'moment';
import { createForm } from 'rc-form';
import { useRequest } from '@/hooks';
// import { useInterviewCandidate } from '@/pages/RecruitEmail/hooks';
import { CONTACT_WAY, BG_RELATE_TYPE } from '@/pages/Recruitment/dictionary';
import { useFormChange } from '@/pages/RecruitEmail/hooks';
import { EditListItem, Button, Picker, PageWrap } from './components';
import { updateBackgroundInfo, deleteBackgroundInfo, getCandidateInfo } from '../service';
import styles from './Register.less';

const BackgroundContacts = ({ maxContactNum, tempBgNum, mobileBgArr, dispatch, location, form }) => {
    const { query } = location;
    const { getFieldProps } = form;
    const [submitLoading, setSubmitLoading] = useState(false);
    const [bitem, setBitem] = useState({});
    // const { data: talentInfo, loading } = useInterviewCandidate(query.nid);
    const { hasFormChange, initialForm } = useFormChange(form);
    const getItemFromDva = () => {
        if (query.itemId === -1 && query.editIndex !== -1 && Reflect.has(mobileBgArr[query.editIndex], 'fakeId')) {
            const tempObj = { ...mobileBgArr[query.editIndex] };
            tempObj.objectName = '';
            setBitem(tempObj);
        }
    };
    React.useEffect(() => {
        // 初始化当前联系人总数
        dispatch({
            type: 'defaultBGList/setTempBgNum',
            newNum: mobileBgArr.length
        });
    }, []);
    const { data: talentInfo, loading } = useRequest(() => getCandidateInfo(query.nid), {
        // 根据id从服务端获取数据
        // manual: true,
        initialData: null,
        formatResult: res => {
            if (res) {
                const { code, data, msg } = res;
                if (code === 10000) {
                    if (data?.recruitTalentBackgrounds?.length > 0) {
                        data.recruitTalentBackgrounds.forEach(item => {
                            if (item.id === Number(query.itemId)) {
                                setBitem(item); // 从请求结果中取出id相同的那项
                            }
                        });
                        getItemFromDva(); // 有填写过背调联系人，但选择的是默认填充项目
                        return data;
                    }
                    getItemFromDva(); // 没有填写过背调联系人
                    return data;
                }
                message.error(msg);
            }
            return undefined;
        },
        onSuccess: () => {
            initialForm();
        }
    });
    const handleLeftClick = () => {
        if (hasFormChange()) {
            Modal.alert('存在未保存的内容，确定退出吗？', '', [
                { text: '取消' },
                {
                    text: '确定',
                    onPress: () => {
                        history.goBack();
                    }
                }
            ]);
        } else {
            history.goBack();
        }
    };

    const getValue = (value, list) => {
        if (value) {
            if (list?.includes(value)) {
                return [value];
            }
            return [-1];
        }
        if (!talentInfo?.workCompanyList?.length) {
            return [-1];
        }
        return undefined;
    };

    const getValueRelateType = (value, list) => {
        let arr = [-1];
        if (value) {
            list.forEach(item => {
                if (item.value === value) {
                    arr = [value];
                }
            });
        } else {
            arr = undefined;
        }
        return arr;
    };

    // useEffect(() => {
    //     if (query.itemId !== -1 && talentInfo?.recruitTalentBackgrounds?.length > 0) {
    //         talentInfo.recruitTalentBackgrounds.forEach(item => {
    //             if (item.id === query.itemId) {
    //                 setBitem(item);
    //             }
    //         });
    //     }
    // }, [talentInfo]);

    // 表格切换效果， 背调公司，联系方式，与你的关系
    const [current, setCurrent] = useState({
        organizationType: getValue(bitem?.organizationName, talentInfo?.workCompanyList),
        objectContactType: bitem?.objectContactType ? [bitem?.objectContactType] : [1],
        relateType: bitem?.relateType ? [bitem.relateType] : undefined
    });
    const contactTitle = {
        1: '电话号码',
        2: '微信号',
        3: 'QQ号',
        4: '邮箱账号',
        99: '联系信息'
    };

    const relateList = BG_RELATE_TYPE.map(item => {
        const newItem = {
            label: item.text,
            value: item.text
        };
        return newItem;
    });

    const currentContactWay = CONTACT_WAY.map(item => {
        const newItem = {
            ...item,
            label: item.text
        };
        return newItem;
    });

    const getCompanyPicker = oldList => {
        const arr = [];
        if (oldList) {
            oldList.forEach(item => {
                arr.push({ label: item, value: item });
            });
        }
        arr.push({ label: '其他', value: -1 });
        return arr;
    };

    const getNewPicker = oldList =>
        oldList ? [...oldList, { label: '其他', value: -1 }] : [{ label: '其他', value: -1 }];

    const formatDate = date => {
        const pad = n => (n < 10 ? `0${n}` : n);
        const dateStr = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(
            date.getHours()
        )}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
        return `${dateStr}`;
    };

    /**
     * 删除默认生成的背调联系人
     */
    const removeDefaultItem = index => {
        dispatch({
            type: 'defaultBGList/deleteOne',
            index
        });
    };

    const handleSubmit = (operationType, flag) => {
        if (operationType === 3) {
            Modal.alert('确定删除此内容？', '', [
                { text: '取消' },
                {
                    text: '确定',
                    onPress: () => {
                        removeDefaultItem(query.editIndex);
                        history.goBack();
                    }
                }
            ]);
            return;
        }
        form.validateFields(async (err, values) => {
            if (!err) {
                // operationType 0 新增, 1 修改，2 删除, 3 删除默认数据
                if (operationType !== 2) {
                    const {
                        organizationName,
                        objectName,
                        relateType,
                        relateTypeName,
                        objectContactType,
                        objectContactInfo,
                        backgroundTime,
                        objectRemark,
                        organizationType
                    } = values;
                    // const { organizationType } = current;
                    const params = {
                        employId: talentInfo.employId,
                        objectName,
                        organizationName: organizationType?.[0] !== -1 ? organizationType[0] : organizationName,
                        relateType: relateType[0] !== -1 ? relateType[0] : relateTypeName,
                        objectContactType: Number(objectContactType),
                        objectContactInfo,
                        backgroundTime: formatDate(backgroundTime),
                        objectRemark,
                        operationType
                    };
                    if (query.itemId !== -1) {
                        params.id = bitem.id;
                    }
                    setSubmitLoading(true);
                    updateBackgroundInfo(params)
                        .then(res => {
                            const { code, msg } = res;
                            if (code === 10000) {
                                dispatch({
                                    type: 'defaultBGList/setTempBgNum',
                                    newNum: tempBgNum + 1
                                });
                                Toast.info('保存成功');
                                if (flag) {
                                    form.resetFields();
                                    // 重置后，滚动条要回到顶部
                                    document.getElementById('scrollContainer').scrollTop = 0;
                                } else {
                                    removeDefaultItem(query.editIndex);
                                    history.goBack();
                                }
                            } else {
                                Toast.info(msg);
                            }
                        })
                        .finally(() => {
                            setSubmitLoading(false);
                        });
                } else {
                    Modal.alert('确定删除此内容？', '', [
                        { text: '取消' },
                        {
                            text: '确定',
                            onPress: () => {
                                const params = {
                                    backgroundId: bitem.id,
                                    employId: talentInfo.employId
                                };
                                deleteBackgroundInfo(params).then(res => {
                                    const { code, msg } = res;
                                    if (code === 10000) {
                                        // Toast.info('提交成功');
                                        if (flag) {
                                            form.resetFields();
                                        } else {
                                            history.goBack();
                                        }
                                    } else {
                                        Toast.info(msg);
                                    }
                                });
                            }
                        }
                    ]);
                }
            } else {
                const tempList = Object.values(err);
                if (tempList && tempList.length > 0) {
                    const { errors } = tempList[0];
                    Toast.info(errors[0]?.message);
                }
            }
        });
    };
    const changeValueFun = (val, type) => {
        setCurrent({
            ...current,
            [type]: val
        });
        // form.setFieldsValue([type], values[type]);
    };

    const renderFooter = () => {
        if (query.itemId === -1 && query.editIndex === -1) {
            if (tempBgNum >= maxContactNum) {
                return null;
            }
            // 新增
            return (
                <>
                    <Button
                        disabled={tempBgNum >= maxContactNum}
                        loading={submitLoading}
                        onClick={() => handleSubmit(0)}
                        style={{ marginRight: 15 }}
                    >
                        保存
                    </Button>
                    <Button
                        disabled={tempBgNum >= maxContactNum}
                        type="primary"
                        loading={submitLoading}
                        onClick={() => handleSubmit(0, true)}
                    >
                        保存并继续添加
                    </Button>
                </>
            );
        }
        if (query.itemId === -1 && query.editIndex !== -1) {
            // 从默认项进入，itemId === -1就代表了这个项目没有上传到服务器，没id嘛。
            return (
                <>
                    <Button loading={submitLoading} onClick={() => handleSubmit(3)} style={{ marginRight: 15 }}>
                        删除
                    </Button>
                    <Button type="primary" loading={submitLoading} onClick={() => handleSubmit(0)}>
                        完成
                    </Button>
                </>
            );
        }
        // 编辑已上传到服务器的
        return (
            <>
                <Button loading={submitLoading} onClick={() => handleSubmit(2)} style={{ marginRight: 15 }}>
                    删除
                </Button>
                <Button type="primary" loading={submitLoading} onClick={() => handleSubmit(1)}>
                    完成
                </Button>
            </>
        );
    };

    return (
        <PageWrap title="背调联系人" navbarProps={{ onLeftClick: handleLeftClick }} footer={renderFooter()}>
            <div style={{ padding: '0 16px' }}>
                <Spin spinning={loading}>
                    <Picker
                        title="背调公司"
                        maskStyle={{ zIndex: 999 }}
                        data={getCompanyPicker(talentInfo?.workCompanyList)}
                        {...getFieldProps('organizationType', {
                            initialValue: getValue(bitem?.organizationName, talentInfo?.workCompanyList),
                            onChange: val => changeValueFun(val, 'organizationType'),
                            rules: [{ required: true, message: '请选择背调公司' }]
                        })}
                    >
                        <EditListItem title="背调公司">请选择</EditListItem>
                    </Picker>
                    {form.getFieldValue('organizationType')?.[0] === -1 && (
                        <EditListItem title="公司名称" showArrow={false}>
                            <InputItem
                                {...getFieldProps('organizationName', {
                                    initialValue: bitem?.organizationName ? `${bitem?.organizationName}` : '',
                                    rules: [{ required: true, message: '请输入公司名称' }]
                                })}
                                clear
                                maxLength={60}
                                placeholder="请输入公司名称"
                            />
                        </EditListItem>
                    )}
                    <EditListItem title="联系人姓名" showArrow={false}>
                        <InputItem
                            {...getFieldProps('objectName', {
                                initialValue: bitem?.objectName || '',
                                rules: [{ required: true, message: '请输入联系人姓名' }]
                            })}
                            clear
                            placeholder="请输入联系人姓名"
                        />
                    </EditListItem>
                    <Picker
                        title="与你的关系"
                        data={getNewPicker(relateList)}
                        {...getFieldProps('relateType', {
                            initialValue: getValueRelateType(bitem?.relateType, relateList),
                            onChange: val => changeValueFun(val, 'relateType'),
                            rules: [{ required: true, message: '请选择与你的关系' }]
                        })}
                    >
                        <EditListItem title="与你的关系">请选择</EditListItem>
                    </Picker>
                    {current?.relateType?.[0] === -1 && (
                        <EditListItem title="关系类型" showArrow={false}>
                            <InputItem
                                {...getFieldProps('relateTypeName', {
                                    initialValue: bitem?.relateTypeName ? `${bitem?.relateTypeName}` : '',
                                    rules: [{ required: true, message: '请输入关系类型' }]
                                })}
                                clear
                                placeholder="请输入"
                            />
                        </EditListItem>
                    )}
                    <Picker
                        title="联系方式"
                        data={currentContactWay}
                        {...getFieldProps('objectContactType', {
                            initialValue: bitem?.objectContactType ? [bitem?.objectContactType] : [1],
                            onChange: val => changeValueFun(val, 'objectContactType'),
                            rules: [{ required: true, message: '请选择联系方式' }]
                        })}
                    >
                        <EditListItem title="联系方式">请选择</EditListItem>
                    </Picker>
                    <EditListItem title={contactTitle[form.getFieldValue('objectContactType')]} showArrow={false}>
                        <InputItem
                            {...getFieldProps('objectContactInfo', {
                                initialValue: bitem?.objectContactInfo ? `${bitem?.objectContactInfo}` : '',
                                rules: [
                                    {
                                        required: true,
                                        message: `请输入${contactTitle[form.getFieldValue('objectContactType')]}`
                                    },
                                    // {
                                    //     pattern: /^[^\s]*$/,
                                    //     message: '禁止输入空格'
                                    // },
                                    {
                                        validator(rule, value, callback) {
                                            const regex = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
                                            if (value && form.getFieldValue('objectContactType')[0] === 4) {
                                                const tempValue = value.trim();
                                                if (regex.test(tempValue)) {
                                                    callback();
                                                } else {
                                                    callback('请输入正确的个人邮箱');
                                                }
                                            }
                                            callback();
                                        }
                                    }
                                ],
                                getValueFromEvent: event => {
                                    if (event.target) {
                                        return event.target.value.replace(/\s+/g, '');
                                    }
                                    return event.replace(/\s+/g, '');
                                }
                            })}
                            clear
                            placeholder="请输入"
                        />
                    </EditListItem>
                    <DatePicker
                        className={styles.customPicker}
                        mode="datetime"
                        title="背调时间"
                        extra="请选择"
                        minDate={new Date()}
                        // maxDate={new Date()}
                        locale={{ okText: '确定', dismissText: '取消' }}
                        {...getFieldProps('backgroundTime', {
                            initialValue: (bitem?.backgroundTime && moment(bitem?.backgroundTime).toDate()) || null,
                            rules: [{ required: true, message: '请选择背调时间' }]
                        })}
                    >
                        <EditListItem title="建议背调时间">请选择</EditListItem>
                    </DatePicker>
                    <EditListItem title="背调对象介绍" showArrow={false} required={false}>
                        <TextareaItem
                            className="customTextarea"
                            autoHeight
                            rows={4}
                            count={1000}
                            {...getFieldProps('objectRemark', {
                                initialValue: bitem?.objectRemark || '',
                                rules: [
                                    {
                                        max: 1000,
                                        message: '请输入'
                                    }
                                ]
                            })}
                            clear
                            placeholder="请输入"
                        />
                    </EditListItem>
                </Spin>
            </div>
        </PageWrap>
    );
};

export default withRouter(
    connect(({ defaultBGList }) => ({
        ...defaultBGList
    }))(createForm()(BackgroundContacts))
);
